// main.js
import './style.css';
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import { XYZ } from 'ol/source';
import VectorLayer from 'ol/layer/Vector';
import Feature from 'ol/Feature'; // 添加此行
import Point from 'ol/geom/Point'; // 添加此行
import { Style, Icon } from 'ol/style'; // 修改此行
import Vector from 'ol/source/Vector'; // 确保正确引用
import Fill from 'ol/style/Fill'
import CircleStyle from 'ol/style/Circle'
import Text from 'ol/style/Text'

const view = new View({
  center: [114.25, 30.59],
  zoom: 6,
  projection: "EPSG:4326"
});

// 高德地图底图
const gaodeSource = new XYZ({
  url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
});
const gaodeLayer = new TileLayer({
  source: gaodeSource
});

const map = new Map({
  target: 'map',
  view,
  layers: [gaodeLayer]
});

// 通过 ol 中提供的要素feature
// 创建要素（点、线、面），并将要素绘制到底图上 feature=>1.几何形状，2.属性信息
// 1.创建一个点要素，并且在这个点要素绘制一个简单的icon,在武汉地图上绘制一个小logo
const iconFeature = new Feature({
  geometry: new Point([114.25, 30.59]),
  // 设置icon的属性信息
  // properties: {
  //   name: 'logo',
  //   type: 'icon'
  // }
});

const canvas = document.createElement('canvas')
canvas.width = 23
canvas.height = 32
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'red'
ctx.beginPath()
// arc指定圆绘制的位置
ctx.arc(11, 16, 10, 0, Math.PI * 2)// 中心点绘制
ctx.fill()

iconFeature.setStyle(new Style({
  image: new Icon({
    img: canvas,
    scale: 1,// 显示的缩放
    imgSize: [30, 30]
  })
}))

const iconSource = new Vector({
  features: [iconFeature]
})
const iconLayer = new VectorLayer({
  source: iconSource
})
map.addLayer(iconLayer)
map.on('click', function (e) {
  const coordinate = e.coordinate
  const iconFeature = new Feature({
    geometry: new Point(coordinate)
  })
  iconFeature.setStyle(new Style({
    image: new CircleStyle({
      radius: 10,
      fill: new Fill({
        color: 'blue'
      })
    }),
    text: new Text({
      text: '文字--圆',
      fill: new Fill({
        color: 'green'
      }),
      offsetY: 20,
      font: 'bold 20px 微软雅黑'
    })
  })
  )
  iconSource.addFeature(iconFeature)
})
// 添加文字的标注